﻿
Imports System.Threading

Public Class multilock
    Public Const defaultLockCount As Int64 = 8192
    Private locks() As Object
    Private Shared MULTILOCK_WAIT_TICKS As Int64

    Shared Sub New()
        MULTILOCK_WAIT_TICKS = counter.registerAverageAndLastAverage("MULTILOCK_WAIT_TICKS", sampleRate:=0.01)
    End Sub

    Public Sub New(ByVal lockCount As Int64)
        ReDim locks(lockCount - 1)
        For i As Int64 = 0 To lockCount - 1
            locks(i) = New Object()
        Next
    End Sub

    Public Sub New()
        Me.New(defaultLockCount)
    End Sub

    Private Function locksigning(Of T)(ByVal i As T) As UInt32
        Return signing(i) Mod locks.Length()
    End Function

    Public Sub lock(Of T)(ByVal i As T)
        Dim startticks As Int64
        startticks = Now.Ticks()
        Dim sign As UInt32
        sign = locksigning(i)
        Try
            Monitor.Enter(locks(sign))
        Catch ex As ThreadAbortException
            raiseError("thread abort.", errorHandle.errorType.warning)
        End Try
        counter.increase(MULTILOCK_WAIT_TICKS, Now.Ticks() - startticks)
    End Sub

    Public Sub release(Of T)(ByVal i As T)
        Monitor.Exit(locks(locksigning(i)))
    End Sub
End Class
